package service;

import exception.BusinessException;
import exception.ErrorEnum;
import model.Item;
import model.Order;
import model.enums.ItemType;
import model.enums.OrderStatus;
import model.UpdataOrder;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;

public class OrderService {

        // 主食类
        Item hamburger = new Item("H001", "汉堡", 15.0, ItemType.MAIN);
        Item fries = new Item("F002", "薯条", 15.0, ItemType.MAIN);
        Item chickenWrap = new Item("W003", "鸡肉卷", 12.0, ItemType.MAIN);

        // 饮料类
        Item icedCoffee = new Item("C004", "冰咖啡", 10.0, ItemType.DRINK);
        Item cola = new Item("C005", "可乐", 8.0, ItemType.DRINK);
        Item orangeJuice = new Item("J006", "橙汁", 9.0, ItemType.DRINK);

        // 甜品类
        Item iceCream = new Item("D007", "冰淇淋", 6.0, ItemType.DESSERT);
        Item cake = new Item("D008", "蛋糕", 12.0, ItemType.DESSERT);

        //当天下午四点时间
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        // 定义下午 4 点的时间
        LocalTime fourPM = LocalTime.of(16, 0);
        // 结合当前日期和下午 4 点的时间创建 LocalDateTime 实例
        LocalDateTime dateTimeAt4PM = LocalDateTime.of(currentDate, fourPM);


    //订单列表
    private static HashMap<String,Order> orderArrayList = new HashMap<>();

    // 创建订单（核心方法）
    public Order createOrder(List<Item> items, boolean isVIP, LocalDateTime currentTime) {

        // 基础校验
        validateItems(items);


        //冰咖啡判断
        for (int i = 0; i < items.size(); i++) {
            if (items.get(i).getName().equals("冰咖啡")){
                if(!dateTimeAt4PM.isAfter(currentTime)){
                    items.remove(i);
                    System.out.println("四点以后不能点冰咖啡，已自动为您取消");
                    i--;
                }
            }
        }

        //价格判断
        double totalPrice = totalPrice(items, isVIP);

        //构建订单
        Order order = new Order(
                UUID.randomUUID().toString(),
                items,
                OrderStatus.CREATED,
                totalPrice,
                currentTime,
                isVIP
        );
        orderArrayList.put(order.getOrderId(),order);
        cancelOrder(order.getOrderId());
        return order;
    }

    //基础校验
    private void validateItems(List<Item> items) {
        //判断是否为空
        if(items==null){
            throw new BusinessException(ErrorEnum.NO_NULL.getMsg());
        }

        //商品数量判断
        if(items.size()>5){
            throw new BusinessException(ErrorEnum.TOO_MANY_ITEMS.getMsg());
        }

        boolean zhushi = true;//是否有主食

        //单独甜品与主食判断
        for (Item item : items) {
            if(item.getType()==ItemType.MAIN){
                zhushi = false;
                break;
            }
        }

        if(zhushi){
            throw new BusinessException(ErrorEnum.DESSERT_ALONE.getMsg());
        }
    }

    //价格判断方法
    public double totalPrice(List<Item> items, boolean isVIP){

        //计数器
        int cofe = 0;//咖啡
        int kele = 0;//可乐
        int cengzhi = 0;//橙汁

        double totalPrice = 0.0;


        //汉堡计数器
        int hanbage = 0;
        //薯条计数器
        int shutiao = 0;

        int pd = 0;
        for (int i = 0; i < items.size(); i++) {

            if(items.get(i).getName().equals("汉堡")){
                hanbage++;
                continue;
            }
            if(items.get(i).getName().equals("薯条")){
                shutiao++;
                continue;
            }
            if(items.get(i).getName().equals("冰咖啡")){
                cofe++;
                continue;
            }
            if(items.get(i).getName().equals("可乐")){
                kele++;
                continue;
            }
            if(items.get(i).getName().equals("橙汁")){
                cengzhi++;
                continue;
            }
            totalPrice += items.get(i).getPrice();
        }

        //饮料处理逻辑
        if (cofe==1){
            totalPrice += 10.0;
        }else if(cofe>1){
            int i = cofe - 2;
            double d = i*10.0;
            totalPrice = totalPrice+ 15.0 + d;
        }
        if (kele==1){
            totalPrice += 10.0;
        }else if(kele>1){
            int i = kele - 2;
            double d = i*8.0;
            totalPrice = totalPrice+12.0 + d;
        }
        if (cengzhi==1){
            totalPrice += 10.0;
        }else if(cengzhi>1){
            int i = cengzhi - 2;
            double d = i*9.0;
            totalPrice = totalPrice+ 13.5 + d;
        }

        //汉堡薯条套餐处理逻辑
        int jishu;//综合计数器
        if(hanbage <= shutiao){
            jishu = hanbage;
            totalPrice+= (shutiao-hanbage)*15.0;
        }else {
            jishu = shutiao;
            totalPrice+= (hanbage-shutiao)*15.0;
        }
        for (int i = 0; i < jishu; i++) {
            totalPrice+=25.0;
        }


        if(isVIP){
            return totalPrice*0.9;
        }else {
            return totalPrice;
        }
    }

    // 取消订单
    public void cancelOrder(String orderId) {
    // 创建一个新线程
        Thread delayedThread = new Thread(() -> {
            try {
                // 线程休眠 30 分钟，1 分钟 = 60000 毫秒，30 分钟 = 30 * 60000 毫秒
                Thread.sleep( 10 * 1000);
            } catch (InterruptedException e) {
                // 捕获线程中断异常
                Thread.currentThread().interrupt();
                return;
            }
            // 30 分钟后执行的任务
            orderArrayList.get(orderId).setStatus(OrderStatus.CANCELLED);
            System.out.println("订单超时，已取消。");
        });

        // 启动线程
        delayedThread.start();
    }

    //查询订单
    public HashMap getAll(){
        return orderArrayList;
    }

    //付款
    public void fukuan(String id){
        orderArrayList.get(id).setStatus(OrderStatus.PAID);
    }

    //修改订单
    public Order updata(UpdataOrder updataOrder, ArrayList<Item> items) {
        Order order = orderArrayList.get(updataOrder.getId());
        Order order2 = new Order(order.getOrderId(),order.getItems(),order.getStatus(),order.getTotalPrice(),order.getCreateTime(),order.getisVIP());
        //查询是否有此订单
        if(order==null){
            throw new BusinessException(ErrorEnum.ORDER_NOT_FOUND.getMsg());
        }

        //判断订单是否已支付
        if(order.getStatus()==OrderStatus.PAID){
            throw new BusinessException(ErrorEnum.MODIFY_FORBIDDEN.getMsg());
        }

        //判断商品是否有效
        if(updataOrder.getUpdatastater().getItem().getStatus()==2){
            throw new BusinessException(ErrorEnum.ITEM_INVALID.getMsg());
        }

        //判断是否为整体替换
        if(updataOrder.getStater().equals("整体替换")){
            Order order1 = createOrder(items, order.getisVIP(), order.getCreateTime());
            order2.setTotalPrice(order1.getTotalPrice());
            order2.setItems(items);
            return order;
        }

        //部分替换
        switch (updataOrder.getUpdatastater().getStater()){
            case "添加商品" :{
                for (int i = 0; i < updataOrder.getUpdatastater().getShuliang(); i++) {
                    order2.getItems().add(updataOrder.getUpdatastater().getItem());
                }
                break;
            }
            case "删除商品" :{
                for (int i = 0; i < updataOrder.getUpdatastater().getShuliang(); i++) {
                    for (int g = 0; g < order.getItems().size(); g++) {
                        if (order2.getItems().get(g).getName().equals(updataOrder.getUpdatastater().getItem().getName())){
                            order2.getItems().remove(g);
                        }
                    }
                }
                break;
            }
        }

        System.out.println("用户想要修改订单，是否同意。1：同意；2：不同意");
        //Scanner scanner = new Scanner(System.in);
        int a =1;
        if(a==2){
            System.out.println("商家拒绝了修改");
            return order;
        }else {
            System.out.println("商家同意修改");
        }

        List<Item> items1 = order2.getItems();
        Order order1 = createOrder(items1, order.getisVIP(), order.getCreateTime());
        order.setItems(items1);
        order.setTotalPrice(order1.getTotalPrice());
        return order;
    }



}